#define MY_DEBUG
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstdlib>

#include <utils.h>

bool check_ip(const char *ip)
{
#define is_num(x) ('0' <= (x) && (x) <= '9')
#define is_dot(x) ((x) == '.')
    int num = 0, dot_cnt = 0;
    char ch = *ip;
    if (!is_num(ch))
    {
        return false;
    }
    for (; *ip; ip++)
    {
        ch = *ip;
        if (is_num(ch))
            num = num * 10 + ch - '0';
        else if (is_dot(ch))
        {
            dot_cnt++;
            if (num < 0 || num > 255 || is_dot(*(ip - 1)))
                return false;
            num = 0;
        }
        else
            return false;
    }
    if (num < 0 || num > 255 || is_dot(*(ip - 1)) || dot_cnt != 3)
        return false;
    return true;
#undef is_num
#undef is_dot
}

void print_log(const char *log)
{

#ifdef MY_DEBUG
    printf("[log] %s\n", log);
    fflush(stdout);
    return;
#else
    static std::ofstream fout("log.txt");
    fout << "[log] " << log << std::endl;
#endif
}

void print_error(const char *error)
{
    fprintf(stderr, "[error] %s\n", error);
    fflush(stderr);
}

char getch()
{
    char ch;
    system("stty -echo");
    system("stty -icanon");
    ch = getchar();
    system("stty icanon");
    system("stty echo");
    return ch;
}

char getche()
{
    char ch;
    system("stty -icanon");
    ch = getchar();
    system("stty icanon");
    return ch;
}

void rand_ch_buf(uchar *ch_buf, int ch_buf_len)
{
    for (int i = 0; i < ch_buf_len; i++)
    {
        ch_buf[i] = rand() % 255;
    }
}